package com.aruba.attendance.initial.viewmodel

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.apkfuns.logutils.LogUtils
import com.aruba.attendance.database.dao.OverworkDurationDao
import com.aruba.attendance.database.dao.RecordDao
import com.aruba.attendance.database.dao.insertOrUpdate
import com.aruba.attendance.database.entity.RecordEntity
import com.aruba.attendance.initial.viewmodel.enums.ConfigState
import com.aruba.attendance.ui.widget.loading.enums.LoadingState
import com.aruba.attendance.util.TimeUtil
import com.ctrip.flight.mmkv.MMKV_KMP
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject

/**
 * 首次进入app的viewModel
 * Created by aruba on 2023/2/10.
 */
@HiltViewModel
class InitialViewModel @Inject constructor(private val kv: MMKV_KMP) : ViewModel() {
    var startTime
        get() = kv.takeString("startTime")
        private set(value) {
            kv["startTime"] = value
        }
    var endTime: String
        get() = kv.takeString("endTime")
        private set(value) {
            kv["endTime"] = value
        }

    // 是否配置了上下班时间
    private var _isConfigTime = mutableStateOf(ConfigState.NOT_CONFIGURED)
    val isTimeConfigured: State<ConfigState>
        get() = _isConfigTime

    @Inject
    lateinit var recordDao: RecordDao

    @Inject
    lateinit var overworkDurationDao: OverworkDurationDao

    fun load() {
        viewModelScope.launch {
            LogUtils.i(startTime + endTime)
            if (startTime.isNotEmpty() && endTime.isNotEmpty()) {
                configComplete()
            }
        }
    }

    fun configComplete() {
        _isConfigTime.value = ConfigState.HAS_CONFIGURED
    }

    @JvmOverloads
    fun saveWorkTime(
        startTime: String,
        endTime: String,
        saveStateCallback: (state: LoadingState) -> Unit = {}
    ) {
        saveStateCallback(LoadingState.Loading)

        viewModelScope.launch {
            LogUtils.i("${startTime} - ${endTime}")

            if (TimeUtil.calcDuration(startTime, endTime) < 0) {
                saveStateCallback(LoadingState.Error("开始时间不能小于结束时间"))
                return@launch
            }

            this@InitialViewModel.startTime = startTime
            this@InitialViewModel.endTime = endTime

            // 计算加班时长
            val date = Calendar.getInstance()
            val year = date.get(Calendar.YEAR)
            val month = date.get(Calendar.MONTH) + 1
            val dayOfMonth = date.get(Calendar.DAY_OF_MONTH)
            val recordList = recordDao.findRecordByDate(year, month, dayOfMonth)
            val lastRecord = recordList.getOrNull(recordList.lastIndex)

            // 如果今日有记录，并且不是周末，计算时长处理
            if (lastRecord != null &&
                (date.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY &&
                        date.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)
            ) {
                val duration = TimeUtil.calcDuration(kv.takeString("endTime"), lastRecord.time)
                // 更新或插入加班时长
                overworkDurationDao.insertOrUpdate(year, month, dayOfMonth, duration)

                // 更新迟到时间
                recordList.getOrNull(0)?.apply {
                    if (RecordEntity.TYPE_GO_WORK == type) {
                        val delayDuration = TimeUtil.calcDuration(
                            kv.takeString("startTime"),
                            time
                        )
                        this.delayDuration = delayDuration
                    }
                }?.let {
                    recordDao.updateRecordById(it)
                }
            }

            delay(500)
            saveStateCallback(LoadingState.Complete)
        }
    }
}